package com.pixel.game.entity;

import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.pixel.game.Utils.PositionUtils;

public class EnemyUnit extends Unit {

    private static final float RANDOM_MOVE_INTERVAL = 3.0f; // 定义随机移动的时间间隔
    private static final float MIN_RANDOM_MOVE_DISTANCE = 50.0f; // 定义敌人随机目标位置与当前位置的最小距离
    private static final float TARGET_REACHED_THRESHOLD = 5.0f; // 定义接近目标位置的距离阈值

    private float attackRange = 50f; // 攻击范围
    private static final float UNIT_SPEED = 50.0f;

    private long randomMoveTimer = 1;//随机移动的时间间隔

    public static final float APPROACH_RANGE = 100.0f; // 敌人接近友军的范围

    public static final float ATTACK_COOLDOWN = 500; // 攻击间隔 500ms

    private static final float baseAttackPower = 20f;

    private static final float baseHealth = 50f;

    public EnemyUnit(Vector2 position, float attackPower, float health, float attackCooldown) {
        super(position, attackPower, health, attackCooldown);
    }

    public EnemyUnit(Vector2 position, int level) {
        super(position, baseAttackPower, baseHealth, ATTACK_COOLDOWN);
        this.setAttackPower(baseAttackPower + 2 * level);
        this.setHealth(baseHealth + 2 * level);
    }

    // 更新敌人的随机目标位置（每隔一段时间）
    public void updateRandomTargetPosition(float deltaTime) {
        this.randomMoveTimer += deltaTime;

        // 如果接近目标位置，或没有目标位置，则生成一个新的目标位置
        if (this.getPosition().dst(this.getTargetPosition()) < TARGET_REACHED_THRESHOLD
            || this.randomMoveTimer >= RANDOM_MOVE_INTERVAL || this.getTargetPosition() == null) {
            Vector2 currentPosition = this.getPosition();
            Vector2 randomTarget;
            float distance;

            do {
                // 生成一个随机目标位置
                float screenWidth = PositionUtils.getScreenWidth();
                float screenHeight = PositionUtils.getScreenHeight();
                randomTarget = new Vector2(MathUtils.random(screenWidth), MathUtils.random(screenHeight));

                // 计算目标位置与当前位置的距离
                distance = currentPosition.dst(randomTarget);
            } while (distance < MIN_RANDOM_MOVE_DISTANCE);

            // 设置新的目标位置
            this.setTargetPosition(randomTarget);
            this.randomMoveTimer = 0;
        }
    }

    // 移动敌人朝向目标位置
    public void moveEnemyTowardsTarget(float deltaTime) {
        Vector2 currentPosition = this.getPosition();
        Vector2 targetPosition = this.getTargetPosition();
        Vector2 direction = new Vector2(targetPosition).sub(currentPosition).nor();
        currentPosition.mulAdd(direction, UNIT_SPEED * deltaTime);
    }


    public float getAttackRange() {
        return attackRange;
    }

    public void setAttackRange(float attackRange) {
        this.attackRange = attackRange;
    }
}
